﻿using System.IO;
using System;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media.Imaging;

namespace Instagram.Version2.Helper
{
    public class Converter
    {
        public static BitmapImage DecodePhoto(byte[] byteVal)
        {
            var memoryStream = new MemoryStream(byteVal);
            var streamImg = new InMemoryRandomAccessStream();

            memoryStream.CopyTo(streamImg.AsStreamForWrite());

            var myBitmapImage = new BitmapImage();
            myBitmapImage.SetSource(streamImg);

            return myBitmapImage;
        }

        async public static Task<byte[]> GetBytes(IStorageFile _photoFile)
        {
            var accessStream = await _photoFile.OpenReadAsync();

            byte[] content;

            using (Stream stream = accessStream.AsStreamForRead((int)accessStream.Size))
            {
                content = new byte[stream.Length];
                await stream.ReadAsync(content, 0, (int)stream.Length);
            }

            return content;
        }

        public static BitmapImage GetImage(byte[] bytes)
        {
            using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
            {
                using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
                {
                    writer.WriteBytes((byte[])bytes);
                    writer.StoreAsync().GetResults();
                }
                var image = new BitmapImage();
                image.SetSource(ms);

                return image;
            }
        }
    }
}
